import { _decorator, AudioSource, Component, log, Node, toDegree, v2, Vec2, warn } from 'cc';
import { Globals } from './Globals';
import { ResourcesUtil } from './ResourcesUtil';
import { Enum_AudioClip } from './Enum';
import StorageManager from './Data/StorageManager';
const { ccclass, property } = _decorator;
// 光波技能
@ccclass('LightWave')
export class LightWave extends Component {
    hurt: number = 999;
    _direction: Vec2 = v2(); // 方向,skillButton传过来的

    private _audioSound: AudioSource;
    get direction(): Vec2 {
        return this._direction;
    }
    set direction(value: Vec2) {
        this._direction = value;
    }

    intervalTime: number = .2; // 间隔时间
    private _intervalTime: number = this.intervalTime;
    private _currIndex: number = 0;

    protected onLoad(): void {
        this._audioSound = this.node.getComponent(AudioSource);
        ResourcesUtil.loadAudioClip(Enum_AudioClip.LightWave).then((clip) => {
            this._audioSound.clip = clip
        })
    }
    onEnable(): void {
        // 初始值
        this._intervalTime = this.intervalTime;
        this._currIndex = 0;

        // 设置旋转的方向
        this.node.angle = toDegree(Math.atan2(this._direction.y, this._direction.x));

        // 子节点旋转
        const nodeAngle = this.node.angle;
        this.node.children.forEach((child, index) => {
            index === 0 ? child.active = true : child.active = false;
            child.angle = -nodeAngle;
        })
    }

    update(deltaTime: number) {
        this.nextChildShow(deltaTime);
    }


    nextChildShow(deltaTime: number) {
        this._intervalTime -= deltaTime;
        if (this._intervalTime <= 0) {
            // 下一个子节点显示
            this.node.children[this._currIndex].active = false;
            this.node.children[++this._currIndex].active = true;
            // 播放个音效
            try {
                if (!this._audioSound || !this._audioSound.clip) {
                    console.log("@@@ loadAudioClip err: ", Enum_AudioClip.LightWave)
                    return;
                }
                StorageManager.instance.sound && this._audioSound.playOneShot(this._audioSound.clip);
            } catch (err) {
                warn(err)
            }
            if (this._currIndex >= this.node.children.length - 1) {
                Globals.putNode(this.node);
                return;
            }
            this._intervalTime = this.intervalTime;
        }
    }
}


